/** @file    WidgetMethods.cpp
 *  @author  Alessandro Polo
 *  @version $Id: WidgetMethods.cpp 2808 2010-07-28 20:44:00Z alex $
 *  @brief
 * File containing methods for the wosh::gui::WidgetMethods class.
 * The header for this class can be found in WidgetMethods.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

 #include "WidgetMethods.h"
 #include "ui_WidgetMethods.h"

 #include <core/Request.h>
 #include <core/Response.h>
 #include <core/MethodsCommon.h>
 #include <core/SecurityManager.h>
 #include <QtGui/QMessageBox>
 #include <QHeaderView>


using namespace std;
namespace wosh {
 namespace gui {

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WidgetMethods::WidgetMethods(QWidget *parent) : QWidget(parent), IWidget()
 {
	this->m_ui = new Ui::WidgetMethods();
	this->m_ui->setupUi(this);

	this->myURI.setName( Utilities::format("%s#%10lu", getClassName(), Utilities::randomLong()) );
	this->myURI.setKernelLocal();

	this->wTableModel = new WoshTableModel(NULL, this);
	this->wTableModel->setPermissionType(Permission::Execute);
	this->m_ui->tableView->setModel(this->wTableModel);

	GenericItemDelegate* tblDelegate = new GenericItemDelegate(this);
	this->m_ui->tableView->setItemDelegate(tblDelegate);

	this->m_ui->wUpBarProps->setEnabled(false);

	connect(this->wTableModel, SIGNAL(tableCell_changed(unsigned int,unsigned int, ISerializable*)), this, SLOT(cell_valueChanged(unsigned int,unsigned int, ISerializable*)));

	//connect(this->m_ui->tableWidget, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(cell_valueChanged(QTableWidgetItem*)));
	connect(this->m_ui->tableView, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(tableView_doubleClicked(const QModelIndex&)));

	connect(this->m_ui->wUpBarProps, SIGNAL(updateClicked()), this, SLOT(refreshSmart()));
}

WidgetMethods::~WidgetMethods()
{
    delete m_ui;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void WidgetMethods::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void WidgetMethods::setTargetURI( const URI& uri )
{
	IWidget::setTargetURI( uri );
	this->m_ui->wUpBarProps->setEnabled(this->getTargetURI().isValid());
}

WRESULT WidgetMethods::reset()
 {
	IWidget::setTargetURI( URI() );
	this->m_ui->wUpBarProps->setEnabled( false );

	this->wTableModel->loadTable(NULL);
	return WRET_OK;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void WidgetMethods::refreshData( bool )
 {
	this->m_ui->wUpBarProps->setEnabled( this->getTargetURI().isValid() );
	if ( !this->getTargetURI().isValid() ) {
		return;
	 }
	Request* request_methods = new Request( _METHOD_ListMethods );
	Message* message = new Message(request_methods);
	message->setDestinationBus( _Bus_ANY );
	postMessageForTarget(message);
	this->m_ui->wUpBarProps->sayRetrieving();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WRESULT WidgetMethods::loadTable( const Table* table )
 {
	this->wTableModel->loadTable(table);

	this->m_ui->tableView->clearSelection();
	this->m_ui->tableView->resizeColumnsToContents();
	this->m_ui->tableView->horizontalHeader()->setResizeMode(1,QHeaderView::Stretch);

	this->m_ui->wUpBarProps->sayReady();
	return WRET_OK;
 }

WRESULT WidgetMethods::updateTable( const Table* table )
 {
	if ( table == NULL )
		return WRET_ERR_PARAM;
	this->m_ui->wUpBarProps->showMessage( QString(tr("Parsing Data [%1 rows]..")).arg(table->getRows()) );

	return WRET_OK;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void WidgetMethods::busMessage( const Message& message, const Bus* )
 {
	if ( message.isEmpty() ) return;
	if ( !message.getContent()->isResponse() ) return;
	if ( !URI::pregMatch( this->myURI, message.getDestination() ) )
		return;
	const wosh::Response* response = message.getContent()->asResponse();

	if ( response->getMethod() == _METHOD_ListMethods ) {
		if ( WFAILED(response->getReturnValue()) ) {
			QMessageBox::critical(this, this->windowTitle(), tr("Error retrieveng Methods (table)") );
			this->m_ui->wUpBarProps->showError( tr("Error retrieving Methods (Table)!") );
			return;
		 }
		if ( response->hasData() && response->getData()->isKindOf<Table>() ) {
			const wosh::Table* propTable = response->getData()->as<Table>();
			loadTable(propTable);
		 }
	 }

 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void WidgetMethods::tableView_doubleClicked( const QModelIndex & index )
 {
	if ( !index.isValid() ) return;
	Table* table = this->wTableModel->getDataTable();
	if ( table == NULL ) return;
	const ISerializable* object = table->get(index.row(), 0 );
	if ( object == NULL ) return;
	if ( !object->isKindOf<Variant>() ) return;
	const wosh::Variant* dataObject = dynamic_cast<const wosh::Variant*>(object);
	if ( dataObject == NULL ) return;

	WidgetMethodCaller* wCaller = new WidgetMethodCaller();
	wCaller->setTargetURI( this->getTargetURI() );
	wCaller->setMethodName( dataObject->toString() );
	wCaller->setMethodDescription( "description" );
	wCaller->show();
 }


//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 }; // namespace gui
}; // namespace wosh
